import { defineStore } from 'pinia'
import { ref, nextTick } from 'vue'
import { teamApi } from '@/api/request'

export const useUserStore = defineStore('user', {
  state: () => ({
    name: '',
    token: '',
    userId: '',
    role: '',
    userTeams: ref([]), // 用户所属的团队列表
    currentTeam: ref(null), // 当前选择的团队
    isLoggedIn: false
  }),

  actions: {
    // 设置token
    setToken(token) {
      this.token = token
    },

    // 设置角色
    setRole(role) {
      this.role = role
    },

    // 设置登录状态
    setLoggedIn(status) {
      this.isLoggedIn = status
    },

    // 重置状态
    resetState() {
      this.name = ''
      this.token = ''
      this.userId = ''
      this.role = ''
      this.userTeams = []
      this.currentTeam = null
      this.isLoggedIn = false
    },

    async setUserInfo(userInfo) {
      // 更新状态
      this.name = userInfo.name
      this.token = userInfo.token
      this.userId = userInfo.userId
      this.role = userInfo.role
      this.isLoggedIn = true

      // 存储到 localStorage 和 sessionStorage
      localStorage.setItem('user-token', userInfo.token)
      sessionStorage.setItem('user-token', userInfo.token)

      // 确保状态已更新
      await nextTick()

      try {
        await this.fetchUserTeams()
      } catch (error) {
        console.error('获取用户团队失败:', error)
      }
    },

    logout() {
      this.name = ''
      this.token = ''
      this.userId = ''
      this.role = ''
      this.userTeams = []
      this.currentTeam = null
      this.isLoggedIn = false
      // 清除所有存储
      localStorage.removeItem('user-token')
      localStorage.removeItem('username')
      sessionStorage.removeItem('user-token')
      window.location.href = '/login'
    },

    // 初始化 store 时检查 token
    initializeStore() {
      // 优先使用 sessionStorage 中的 token
      const sessionToken = sessionStorage.getItem('user-token')
      const localToken = localStorage.getItem('user-token')
      const username = localStorage.getItem('username')

      if (sessionToken) {
        this.token = sessionToken
        this.isLoggedIn = true
        // 恢复用户名
        if (username) {
          this.name = username
        }
      } else if (localToken) {
        // 如果 sessionStorage 中没有但 localStorage 中有，则同步到 sessionStorage
        this.token = localToken
        this.isLoggedIn = true
        sessionStorage.setItem('user-token', localToken)
        // 恢复用户名
        if (username) {
          this.name = username
        }
      }
    },

    // 获取用户所属的团队列表
    async fetchUserTeams() {
      try {
        const response = await teamApi.getTeams()
        if (response.data.code === 200) {
          this.userTeams = response.data.data || []
          if (this.userTeams.length > 0) {
            this.currentTeam = this.userTeams[0]
          }
        }
      } catch (error) {
        console.error('获取用户团队失败:', error)
        throw error
      }
    },

    // 切换当前团队
    switchTeam(teamId) {
      const team = this.userTeams.find((t) => t.id === teamId)
      if (team) {
        this.currentTeam = team
      }
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage
      }
    ]
  }
})
